package com.ctim.web.config;

import com.ctim.common.exception.EnumPcsService;
import com.ctim.common.pcs.PcsResult;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.tomcat.util.http.fileupload.FileUploadBase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice()
public class ControllerExceptionHandler extends ResponseEntityExceptionHandler {

    private static final Logger _logger = LoggerFactory.getLogger(ControllerExceptionHandler.class);

    @ResponseBody
    @ExceptionHandler(value = {Exception.class})
    PcsResult handleControllerException(HttpServletRequest request, Throwable ex) {
        if (ex instanceof UnauthorizedException) {
            return new PcsResult(EnumPcsService.ACCESS_UNAUTHORIZED);
        } else if(ex instanceof MultipartException) {// 附件异常
            if (ex.getCause().getCause() instanceof FileUploadBase.SizeLimitExceededException ) {// 文件上限
                return new PcsResult(EnumPcsService.BUSINESS_FILE_MAXIMUM);
            }
            return new PcsResult(EnumPcsService.ERROR_OPERATE);
        } else {
            _logger.error("operate fail",ex);
            return new PcsResult(EnumPcsService.ERROR_OPERATE);
        }
    }

}